package com.sys.controller;

import com.sys.Utils.AdminUserUtils;
import com.sys.dao.AdminUserMapper;
import com.sys.dao.ImageMapper;
import com.sys.domain.AdminRole;
import com.sys.domain.AdminUser;
import com.sys.domain.Image;
import com.sys.result.PageParam;
import com.sys.result.RequestPageVo;
import com.sys.result.RequestResultVo;
import com.sys.service.AdminRoleService;
import com.sys.service.AdminUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/user")
public class AdminUserController {

    private static final Logger log = LoggerFactory.getLogger(AdminUserController.class);

    @Resource
    private AdminUserMapper adminUserMapper;
    @Resource
    private AdminUserService userService;

    @Resource
    private AdminRoleService roleService;
    @Resource
    private ImageMapper imageMapper;

    @RequestMapping("/userPage")
    public String userPage(Model model, @RequestParam(value = "title", required = false) String title) {
        model.addAttribute("title", title);
        return "auth/user";
    }

    @RequestMapping("/queryUser")
    public @ResponseBody
    RequestPageVo<AdminUser> queryUser(@ModelAttribute(value = "param") PageParam param, @ModelAttribute(value = "user") AdminUser user) {
        return userService.findUserPageList(user, param);
    }

    @RequestMapping("/saveOrUpdate")
    public @ResponseBody
    RequestResultVo<AdminUser> saveOrUpdate(@ModelAttribute("user") AdminUser user, @RequestParam(required = false, value = "contractFile") MultipartFile contractFile, HttpServletRequest request) {
        RequestResultVo<AdminUser> result = new RequestResultVo<AdminUser>();
        try {
            if (user != null) {
                if (contractFile != null && contractFile.getSize() > 0) {
                    if (contractFile.getSize() <= 2097152) {
                        String type = contractFile.getContentType();
                        if ("image".equals(type.substring(0, type.indexOf("/")))) {
                            String fileName = contractFile.getOriginalFilename();
                            if (!StringUtils.isEmpty(fileName)) {
                                Image image = new Image();
                                image.setImage(contractFile.getBytes());
                                AdminUser louser = adminUserMapper.selectByPrimaryKey(user.getId());
                                // 查询之前是否有图片
                                if (louser.getAvatar() != null && !"0".equals(louser.getAvatar())) {
                                    // 删除之前的
                                    image.setId(Integer.valueOf(louser.getAvatar()));
                                    imageMapper.updateByPrimaryKeySelective(image);
                                } else {
                                    imageMapper.insert(image);
                                    user.setAvatar(image.getId().toString());
                                }
                            }
                        } else {
                            result.setSuccess(false);
                            result.setErrorMessage("上传的图片格式不正确");
                            return result;
                        }
                    } else {
                        result.setSuccess(false);
                        result.setErrorMessage("上传文件大小不能超过2M");
                        return result;
                    }
                }
                String name = AdminUserUtils.getAdminUserName(request);
                if (user.getId() != null) {
                    user.setModifier(name);
                    return userService.updateUser(user);
                } else {
                    user.setCreator(name);
                    return userService.insertUser(user);
                }
            } else {
                result.setSuccess(false);
                result.setErrorMessage("用户信息不能为空！");
            }
        } catch (Exception e) {
            log.error("", e);
        }
        return result;
    }

    @RequestMapping("/deleteUser")
    public @ResponseBody
    RequestResultVo<AdminUser> deleteUser(@RequestParam("id") Long id) {
        return userService.deleteUser(id);
    }

    @RequestMapping("/userRolePage")
    public String userRolePage(@RequestParam("id") Long id, Model model) {
        model.addAttribute("id", id);
        List<AdminRole> rList = roleService.findRoleByUserId(id);
        List<AdminRole> nList = roleService.findRoleByNonUserId(id);
        model.addAttribute("rList", rList);
        model.addAttribute("nList", nList);
        return "auth/userRole";
    }

    @RequestMapping("/queryUserRole")
    public @ResponseBody
    RequestResultVo<Map<String, List<AdminRole>>> queryUserRole(@RequestParam("id") Long id) {
        RequestResultVo<Map<String, List<AdminRole>>> reuslt = new RequestResultVo<Map<String, List<AdminRole>>>();
        List<AdminRole> rList = roleService.findRoleByUserId(id);
        List<AdminRole> nList = roleService.findRoleByNonUserId(id);
        Map<String, List<AdminRole>> map = new HashMap<String, List<AdminRole>>();
        map.put("userRole", rList);
        map.put("nonUserRole", nList);
        reuslt.setResult(map);
        return reuslt;
    }

    @RequestMapping("/deleteUserRole")
    public @ResponseBody
    RequestResultVo<AdminRole> deleteUserRole(@RequestParam("roleIds[]") List<Long> roleIds, @RequestParam("userId") Long userId) {
        return userService.deleteUserRole(roleIds, userId);
    }

    @RequestMapping("/addUserRole")
    public @ResponseBody
    RequestResultVo<AdminRole> addUserRole(@RequestParam("roleIds[]") List<Long> roleIds, @RequestParam("userId") Long userId) {
        return userService.addUserRole(roleIds, userId);
    }

    @RequestMapping("/resetPassword")
    public @ResponseBody
    RequestResultVo<AdminUser> resetPassword(@RequestParam("id") Long id) {
        return userService.resetUserPassword(id);
    }

    @RequestMapping("/profile")
    public String profile(Model model, HttpServletRequest request) {
        String name = (String) request.getSession().getAttribute("username");
        AdminUser user = userService.findUserByLoginName(name);
        model.addAttribute("user", user);
        return "user/profile";
    }

    @RequestMapping("/updatePassword")
    public @ResponseBody
    RequestResultVo<String> updatePassword(@RequestParam String oldPassword, @RequestParam String password, HttpServletRequest request) {
        String name = (String) request.getSession().getAttribute("username");
        return userService.updatePassword(name, oldPassword, password);
    }

    @RequestMapping("/userImage")
    public void getUserImage(HttpServletResponse response, Integer id) {
        Image image = imageMapper.selectByPrimaryKey(id);
        byte[] data = image.getImage();
        response.setContentType("img/jpeg");
        response.setCharacterEncoding("utf-8");
        try {
            OutputStream outputStream = response.getOutputStream();
            InputStream in = new ByteArrayInputStream(data);
            int len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
